package com.qztc.news_end_customer.controller;

import com.qztc.news_end_customer.config.GlobalConfig;
import com.qztc.news_end_dto.dto.News;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/thenews/news")
public class NewsControllerByRestTemplate extends GlobalConfig {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/show")
    public String show(){
        return restTemplate.getForObject(SEVICE_URL+"news/show", String.class);
    }

    @GetMapping("/getbythemeid")
    public String getbythemeid(@RequestParam Integer themeid){
        return restTemplate.getForObject(SEVICE_URL+"news/getbythemeid?themeid=" + themeid, String.class);
    }

    @GetMapping("/getbynewsid")
    public String getbynewsid(@RequestParam Integer newsid){
        return restTemplate.getForObject(SEVICE_URL+"news/getbynewsid?newsid=" + newsid, String.class);
    }

    @PostMapping("/add")
    public String add(@RequestBody News news){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<News> httpEntity = new HttpEntity<>(news,headers);
        ResponseEntity<String> result = restTemplate.exchange(SEVICE_URL+"news/add", HttpMethod.POST,httpEntity,String.class);
        return result.getBody();
    }

    @PutMapping("/update")
    public String update(@RequestBody News news){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<News> httpEntity = new HttpEntity<>(news,headers);
        ResponseEntity<String> result = restTemplate.exchange(SEVICE_URL+"news/update", HttpMethod.PUT,httpEntity,String.class);
        return result.getBody();
    }

    @DeleteMapping("/deletebynewsid")
    public String deletebynewsid(@RequestBody News news){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<News> httpEntity = new HttpEntity<>(news,headers);
        ResponseEntity<String> result = restTemplate.exchange(SEVICE_URL+"news/deletebynewsid", HttpMethod.DELETE,httpEntity,String.class);
        return result.getBody();
    }
}
